<?php
namespace app\api\controller;
use \think\facade\Db;
use app\server\XwechatServerServer;
class User extends Base
{
    /**
     * 微信用户登录
     * @return void
     */
    public function wxlogin(){
        $params = input();
        $app = $params['app']??'';
        $code = $params['code']??'';
        $table = $this->getUserTable($app);
        if(empty($code)){
            $data['uuid'] = time() . mt_rand(0, 99999);
            add($table, $data);
        }else{
            $response = app(XwechatServerServer::class)->getUserOpenId($app, $code);
            $data = [
                'uuid' => $response['openid'] ?? "openid_" . time() . mt_rand(1, 9),
                'session_key' => $response['session_key'] ?? "session_key_" . time() . mt_rand(1, 9),
                'type' => 1
            ];
            $map = ['uuid' => $data['uuid']];
            $row = find($table, 'code,uuid', $map);
            if (!empty($row)) {
                $data = $row;
            } else {
                add($table, $data);
            }
        }
        $this->success('success',$data);
    }
    /**
     * 获取用户表
     * @param $appName
     * @return string
     */
    protected function getUserTable($appName): string
    {
        return 'app_wx_'.$appName.'_user';
    }
    /**
     * 投诉与建议
     * @return null
     */
    public function complaint(){
        $type = input('type','');
        $uuid = input('uuid',0);
        if(empty($uuid)){
            $this->error("非法传参");
        }
        $complaint = input('complaint','');
        $phone = input('phone','');
        if(empty($complaint)){
            $this->error("请输入内容");
        }
        if(empty($phone)){
            $this->error("请输入手机号码");
        }
        $pattern = "/1(\d{10})/";
        if (!preg_match($pattern, $phone)){
            $this->error("手机号码格式错误");
        }
        $data = [
            'uuid'=>$uuid,
            'app_name'=>$this->app,
            'telephone'=>$phone,
            'complaint'=>$complaint
        ];
        Db::table('app_complaint')->insert($data);
        return $this->success('success');
    }



}
